<template>
    <view class="main">
        <!--地址  -->
        <tn-picker v-model="addressValue" v-model:open="props.show" :data="props.address" value-key="id"
            label-key="name" mask cancel-color="#eb4869" confirm-color="#388095" @confirm="confirm"
            @close="emit('close', false)" @cancel="emit('close', false)" @change="change" />
    </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const props = defineProps<{
    show?: boolean,
    address: any
}>()

// piker 数据类型
interface TPikerType {
    name: string,
    id: number,
    children?: TPikerType[]
}

// 递归查找name
const findNamesByIds = (ids: number[], data: TPikerType[]) => {
    const names: string[] = [];
    // 递归函数，用于在嵌套结构中查找ID  
    function findByName(currentData: any, idsToFind: any) {
        for (const item of currentData) {
            if (idsToFind.includes(item.id)) {
                names.push(item.name);
                // 如果当前项有子项，并且我们还没有找到所有的ID，则递归查找  
                if (item.children && idsToFind.length > names.length) {
                    findByName(item.children, idsToFind.filter((id: number) => !names.some(nameItem => nameItem.includes(id.toString()))));
                }
            }
        }
    }
    // 调用递归函数  
    findByName(data, ids);
    return names;
}
// 获取地址数
let addressValue = ref<number | string | number[]>()
let addressName = ref<string>('')

const emit = defineEmits(['setValue', 'close'])
const confirm = (id: number[]) => {
    addressName.value = findNamesByIds(id as number[], props.address).join('-')
    emit('setValue', { name: addressName.value, idList: addressValue.value })
    emit('close', false)
}

const change = (id: number[]) => {
    addressName.value = findNamesByIds(id as number[], props.address).join('-')
    emit('setValue', { name: addressName.value, idList: addressValue.value })
}
</script>
<style lang="scss" scoped></style>